package utils;

import entity.Score;
import entity.Student;
import service.ScoreManager;
import service.StudentManager;

import java.time.LocalDate;
import java.util.Scanner;

/**
 * 输入工具类
 */
public class ScannerUtil {
    private final ScoreManager scoreManager;
    private final StudentManager studentManager;
    private final Scanner scanner = new Scanner(System.in);
    
    public ScannerUtil(ScoreManager scoreManager, StudentManager studentManager) {
        this.scoreManager = scoreManager;
        this.studentManager = studentManager;
    }
    /**
     * 带验证的添加学生方法
     */
    public  void addStudentWithValidation() {
        String studentId = getValidStudentId(true);
        if (studentId == null) return;

        String name = getValidName();
        if (name == null) return;

        int age = getValidAge();
        if (age == -1) return;

        String major = getValidMajor();
        if (major == null) return;

        LocalDate enrollDate = getValidDate();
        if (enrollDate == null) return;

        Student newStudent = new Student(studentId, name, age, major, enrollDate);
        studentManager.addStudent(newStudent);
    }

    /**
     * 获取有效的学号
     *
     * @param checkDuplicate 是否检查重复
     * @return 有效的学号，如果验证失败返回null
     */
    public String getValidStudentId(boolean checkDuplicate) {
        while (true) {
            System.out.print("请输入学号：");
            String studentId = scanner.nextLine();

            String errorMsg;
            if (checkDuplicate) {
                errorMsg = ValidationUtil.validateStudentId(studentId, studentManager.getStudentMap());
            } else {
                errorMsg = ValidationUtil.validateStudentIdExists(studentId, studentManager.getStudentMap());
            }

            if (errorMsg == null) {
                return studentId.trim();
            } else {
                System.out.println("错误：" + errorMsg);
                System.out.print("是否重新输入？(y/n)：");
                if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                    return null;
                }
            }
        }
    }

    /**
     * 获取有效的姓名
     * @return 有效的姓名，如果验证失败返回null
     */
    public  String getValidName() {
        while (true) {
            System.out.print("请输入姓名：");
            String name = scanner.nextLine();

            String errorMsg = ValidationUtil.validateName(name);
            if (errorMsg == null) {
                return name.trim();
            } else {
                System.out.println("错误：" + errorMsg);
                System.out.print("是否重新输入？(y/n)：");
                if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                    return null;
                }
            }
        }
    }

    /**
     * 获取有效的年龄
     *
     * @return 有效的年龄，如果验证失败返回-1
     */
    public  int getValidAge() {
        while (true) {
            System.out.print("请输入年龄：");
            String ageInput = scanner.nextLine();

            try {
                int age = Integer.parseInt(ageInput);
                String errorMsg = ValidationUtil.validateAge(age);
                if (errorMsg == null) {
                    return age;
                } else {
                    System.out.println("错误：" + errorMsg);
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：年龄必须是整数");
            }

            System.out.print("是否重新输入？(y/n)：");
            if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                return -1;
            }
        }
    }

    /**
     * 获取有效的专业
     *
     * @return 有效的专业，如果验证失败返回null
     */
    public  String getValidMajor() {
        while (true) {
            System.out.print("请输入专业：");
            String major = scanner.nextLine();

            String errorMsg = ValidationUtil.validateMajor(major);
            if (errorMsg == null) {
                return major.trim();
            } else {
                System.out.println("错误：" + errorMsg);
                System.out.print("是否重新输入？(y/n)：");
                if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                    return null;
                }
            }
        }
    }

    /**
     * 获取有效的日期
     *
     * @return 有效的日期，如果验证失败返回null
     */
    public LocalDate getValidDate() {
        while (true) {
            try {
                System.out.print("请输入入学年份(如2021)：");
                int year = Integer.parseInt(scanner.nextLine());
                System.out.print("请输入入学月份(如9)：");
                int month = Integer.parseInt(scanner.nextLine());
                System.out.print("请输入入学日期(如1)：");
                int day = Integer.parseInt(scanner.nextLine());

                String errorMsg = ValidationUtil.validateDate(year, month, day);
                if (errorMsg == null) {
                    return LocalDate.of(year, month, day);
                } else {
                    System.out.println("错误：" + errorMsg);
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：请输入有效的数字");
            }

            System.out.print("是否重新输入？(y/n)：");
            if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                return null;
            }
        }
    }

    /**
     * 带验证的成绩录入方法
     */
    public  void addScoreWithValidation() {
        String studentId = getValidStudentId(false); // 检查学生是否存在
        if (studentId == null) return;

        // 检查是否已存在成绩
        String duplicateError = ValidationUtil.validateScoreNotExists(studentId, scoreManager.getScores());
        if (duplicateError != null) {
            System.out.println("错误：" + duplicateError);
            return;
        }

        double chinese = getValidScore("语文");
        if (chinese == -1) return;

        double math = getValidScore("数学");
        if (math == -1) return;

        double english = getValidScore("英语");
        if (english == -1) return;

        Score newScore = new Score(studentId, chinese, math, english);
        scoreManager.addScore(newScore);
    }

    /**
     * 获取有效的成绩
     *
     * @param subjectName 科目名称
     * @return 有效的成绩，如果验证失败返回-1
     */
    public double getValidScore(String subjectName) {
        while (true) {
            System.out.print("请输入" + subjectName + "成绩：");
            String scoreInput = scanner.nextLine();

            try {
                double score = Double.parseDouble(scoreInput);
                String errorMsg = ValidationUtil.validateScore(score, subjectName);
                if (errorMsg == null) {
                    return score;
                } else {
                    System.out.println("错误：" + errorMsg);
                }
            } catch (NumberFormatException e) {
                System.out.println("错误：成绩必须是数字");
            }

            System.out.print("是否重新输入？(y/n)：");
            if (!scanner.nextLine().toLowerCase().startsWith("y")) {
                return -1;
            }
        }
    }

    /**
     * 带验证的修改学生信息方法
     */
    public  void updateStudentWithValidation() {
        System.out.print("请输入要修改的学号：");
        String studentId = scanner.nextLine();

        // 检查学生是否存在
        if (!studentManager.getStudentMap().containsKey(studentId)) {
            System.out.println("错误：学号不存在");
            return;
        }

        String name = getValidName();
        if (name == null) return;

        int age = getValidAge();
        if (age == -1) return;

        String major = getValidMajor();
        if (major == null) return;

        LocalDate enrollDate = getValidDate();
        if (enrollDate == null) return;

        Student updStudent = new Student(studentId, name, age, major, enrollDate);
        studentManager.updateStudent(updStudent);
    }

    /**
     * 带验证的修改成绩方法
     */
    public void updateScoreWithValidation() {
        System.out.print("请输入要修改成绩的学号：");
        String studentId = scanner.nextLine();

        // 检查学生是否存在
        if (!studentManager.getStudentMap().containsKey(studentId)) {
            System.out.println("错误：学号不存在");
            return;
        }

        // 检查成绩是否存在
        if (!scoreManager.getScores().containsKey(studentId)) {
            System.out.println("错误：该学生没有成绩记录");
            return;
        }

        double chinese = getValidScore("语文");
        if (chinese == -1) return;

        double math = getValidScore("数学");
        if (math == -1) return;

        double english = getValidScore("英语");
        if (english == -1) return;

        Score updScore = new Score(studentId, chinese, math, english);
        scoreManager.updateScore(updScore);
    }
}